<?php
namespace backend\models\activeRecords;

use common\libs\Constants;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%guild_game}}".
 *
 * @property string $id 自增id
 * @property string $guild_sign 所属公会标识
 * @property int $game_id 游戏ID
 * @property integer $is_delete 是否删除
 */
class GuildGame extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%guild_game}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['guild_sign', 'game_id'], 'required'],
            [['game_id','is_delete'], 'integer'],
            [['guild_sign'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', '自增id'),
            'guild_sign' => Yii::t('app', '所属公会标识'),
            'game_id' => Yii::t('app', '游戏ID'),
        ];
    }

    public function getGame(){
        return $this->hasOne(TGame::className(),['game_id'=>'game_id']);
    }

    public function insertGameList($params){
        $rows = [];
        foreach($params['gameList'] as $value){
            $rows[] = [
                'guild_sign'=>$params['guildSign'],
                'game_id'=>$value
            ];
        }
        $flag = Yii::$app->db->createCommand()
            ->batchInsert(GuildGame::tableName(),['guild_sign','game_id'],$rows)->execute();
        return $flag;
    }

    public function removeGame($params){
        $flag = Constants::Status_Success;
        foreach($params['gameList'] as $value){
            $guildGameModel = new GuildGame();
            $guildGameInfo = $guildGameModel->find()
            ->where('guild_sign = :guild_sign',[':guild_sign'=>$params['guildSign']])
            ->andWhere('game_id = :game_id',[':game_id'=>$value])
            ->andWhere('is_delete = :is_delete',[':is_delete'=>Constants::YesNo_No])
            ->one();
            $guildGameInfo->is_delete = Constants::YesNo_Yes;
            if(!$guildGameInfo->save()){
                $flag = Constants::Status_Faild;
            }
        }
        return $flag;
    }

    public static function getGameList()
    {
        $model = self::find()
            ->where('guild_sign = :guild_sign',[':guild_sign'=>Yii::$app->user->getIdentity()->parent])
            ->andWhere('is_delete = :is_delete',[':is_delete'=>Constants::YesNo_No])
            ->all();
        $list = [];
        foreach($model as $value){
            $list[$value->game_id] = $value->game->game_name;
        }
        return $list;
    }

}
